/*
 * Wazuh Vulnerability Scanner - Unit Tests
 * Copyright (C) 2015, Wazuh Inc.
 * March 5, 2024.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation.
 */

#include "eventPackageAlertDetailsBuilder_test.hpp"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_deltas_generated.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_deltas_schema.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_synchronization_generated.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_synchronization_schema.h"
#include "../scanOrchestrator/eventPackageAlertDetailsBuilder.hpp"
#include "MockDatabaseFeedManager.hpp"
#include "MockOsDataCache.hpp"
#include "TrampolineOsDataCache.hpp"
#include "flatbuffers/flatbuffer_builder.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "json.hpp"
#include <unistd.h>

using ::testing::_;
using ::testing::HasSubstr;
using ::testing::ThrowsMessage;

namespace NSEventPackageAlertDetailsBuilderTest
{
    constexpr auto TEST_DESCRIPTION_DATABASE_PATH {"queue/vd/descriptions"};

    const std::string DELTA_PACKAGES_INSERTED_MSG =
        R"(
            {
                "agent_info": {
                    "agent_id": "001",
                    "agent_ip": "192.168.33.20",
                    "agent_name": "focal",
                    "agent_version": "4.7.1",
                    "node_name": "node01"
                },
                "data_type": "dbsync_packages",
                "data": {
                    "architecture": "amd64",
                    "checksum": "1e6ce14f97f57d1bbd46ff8e5d3e133171a1bbce",
                    "description": "library for GIF images library",
                    "format": "deb",
                    "groups": "libs",
                    "item_id": "ec465b7eb5fa011a336e95614072e4c7f1a65a53",
                    "multiarch": "same",
                    "name": "libgif7",
                    "priority": "optional",
                    "scan_time": "2023/08/04 19:56:11",
                    "size": 72,
                    "source": "giflib",
                    "vendor": "Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>",
                    "version": "5.1.9-1",
                    "install_time": "1577890801",
                    "location":" "
                },
                "operation": "INSERTED"
            }
        )";

    const std::string DELTA_PACKAGES_DELETED_MSG =
        R"(
            {
                "agent_info": {
                    "agent_id": "001",
                    "agent_ip": "192.168.33.20",
                    "agent_version": "4.7.1",
                    "agent_name": "focal",
                    "node_name": "node01"
                },
                "data_type": "dbsync_packages",
                "data": {
                    "architecture": "amd64",
                    "checksum": "1e6ce14f97f57d1bbd46ff8e5d3e133171a1bbce",
                    "description": "library for GIF images library",
                    "format": "deb",
                    "groups": "libs",
                    "item_id": "ec465b7eb5fa011a336e95614072e4c7f1a65a53",
                    "multiarch": "same",
                    "name": "libgif7",
                    "priority": "optional",
                    "scan_time": "2023/08/04 19:56:11",
                    "size": 72,
                    "source": "giflib",
                    "vendor": "Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>",
                    "version": "5.1.9-1",
                    "install_time": "1577890801",
                    "location":" "
                },
                "operation": "DELETED"
            }
        )";

    const std::string CVEID {"CVE-2024-1234"};
} // namespace NSEventPackageAlertDetailsBuilderTest

using namespace NSEventPackageAlertDetailsBuilderTest;

void EventPackageAlertDetailsBuilderTest::SetUp()
{
    std::filesystem::create_directories("queue/vd");

    // Policy manager initialization.
    const auto& configJson {nlohmann::json::parse(R"({
    "vulnerability-detection": {
        "enabled": "yes",
        "index-status": "yes",
        "cti-url": "cti-url.com"
    },
    "osdataLRUSize":1000
    })")};
    PolicyManager::instance().initialize(configJson);
}

void EventPackageAlertDetailsBuilderTest::TearDown()
{
    spOsDataCacheMock.reset();
    PolicyManager::instance().teardown();
    std::filesystem::remove_all("queue/vd");
}

TEST_F(EventPackageAlertDetailsBuilderTest, TestSuccessfulPackageInsertedCVSS2)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "2",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_INSERTED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));
    auto scanContext = std::make_shared<TScanContext<TrampolineOsDataCache>>(syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"INSERTED"})"_json;
    scanContext->m_matchConditions[CVEID] = {"1.0.0", MatchRuleCondition::Equal};

    TEventPackageAlertDetailsBuilder<MockDatabaseFeedManager, TScanContext<TrampolineOsDataCache>>
        eventPackageAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(eventPackageAlertDetailsAugmentation.handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);
    EXPECT_NE(scanContext->m_elements.find(CVEID), scanContext->m_elements.end());

    auto& element = scanContext->m_elements[CVEID];

    EXPECT_STREQ(element.at("operation").get_ref<const std::string&>().c_str(), "INSERTED");
    std::string elementId = std::string(scanContext->agentNodeName()) + "_" + std::string(scanContext->agentId()) +
                            "_" + std::string(scanContext->packageItemId()) + "_" + CVEID;

    EXPECT_EQ(scanContext->m_alerts.size(), 1);
    EXPECT_NE(scanContext->m_alerts.find(CVEID), scanContext->m_alerts.end());

    auto& alert = scanContext->m_alerts[CVEID];

    std::string alertScoreVersion {"cvss2"};

    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("access_complexity")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->accessComplexity()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("authentication")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->authentication()->c_str());

    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("availability")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->availabilityImpact()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("confidentiality_impact")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->confidentialityImpact()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("integrity_impact")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->integrityImpact()->c_str());

    EXPECT_STREQ(alert.at("vulnerability").at("assigner").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->assignerShortName()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("cwe_reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->cweId()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("source").get_ref<const std::string&>().c_str(),
                 scanContext->packageSource().data());
    EXPECT_STREQ(alert.at("vulnerability").at("rationale").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->description()->c_str());

    EXPECT_STREQ(alert.at("vulnerability").at("cve").get_ref<const std::string&>().c_str(), CVEID.c_str());

    EXPECT_DOUBLE_EQ(
        alert.at("vulnerability").at("cvss").at(alertScoreVersion).at("base_score").get_ref<const double&>(),
        Utils::floatToDoubleRound(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scoreBase(), 2));

    EXPECT_STREQ(alert.at("vulnerability").at("enumeration").get_ref<const std::string&>().c_str(), "CVE");
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("architecture").get_ref<const std::string&>().c_str(),
                 scanContext->packageArchitecture().data());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("name").get_ref<const std::string&>().c_str(),
                 scanContext->packageName().data());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("version").get_ref<const std::string&>().c_str(),
                 scanContext->packageVersion().data());

    EXPECT_STREQ(alert.at("vulnerability").at("published").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->datePublished()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->reference()->c_str());
    EXPECT_STREQ(
        alert.at("vulnerability").at("severity").get_ref<const std::string&>().c_str(),
        Utils::toSentenceCase(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->severity()->str()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("status").get_ref<const std::string&>().c_str(), "Active");

    EXPECT_STREQ(alert.at("vulnerability").at("title").get_ref<const std::string&>().c_str(),
                 (CVEID + " affects " + scanContext->packageName().data()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("type").get_ref<const std::string&>().c_str(), "Packages");
    EXPECT_STREQ(alert.at("vulnerability").at("updated").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->dateUpdated()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("condition").get_ref<const std::string&>().c_str(),
                 "Package equal to 1.0.0");
}

TEST_F(EventPackageAlertDetailsBuilderTest, TestSuccessfulPackageInsertedCVSS3)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_INSERTED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));
    auto scanContext = std::make_shared<TScanContext<TrampolineOsDataCache>>(syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"INSERTED"})"_json;
    scanContext->m_matchConditions[CVEID] = {"1.0.0", MatchRuleCondition::LessThan};

    TEventPackageAlertDetailsBuilder<MockDatabaseFeedManager, TScanContext<TrampolineOsDataCache>>
        eventPackageAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(eventPackageAlertDetailsAugmentation.handleRequest(scanContext));

    auto& alert = scanContext->m_alerts[CVEID];

    std::string alertScoreVersion {"cvss3"};

    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("attack_vector")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->attackVector()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("privileges_required")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->privilegesRequired()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("scope")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scope()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("user_interaction")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->userInteraction()->c_str());

    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("availability")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->availabilityImpact()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("confidentiality_impact")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->confidentialityImpact()->c_str());
    EXPECT_STREQ(alert.at("vulnerability")
                     .at("cvss")
                     .at(alertScoreVersion)
                     .at("vector")
                     .at("integrity_impact")
                     .get_ref<const std::string&>()
                     .c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->integrityImpact()->c_str());

    EXPECT_STREQ(alert.at("vulnerability").at("assigner").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->assignerShortName()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("cwe_reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->cweId()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("source").get_ref<const std::string&>().c_str(),
                 scanContext->packageSource().data());
    EXPECT_STREQ(alert.at("vulnerability").at("rationale").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->description()->c_str());

    EXPECT_STREQ(alert.at("vulnerability").at("cve").get_ref<const std::string&>().c_str(), CVEID.c_str());

    EXPECT_DOUBLE_EQ(
        alert.at("vulnerability").at("cvss").at(alertScoreVersion).at("base_score").get_ref<const double&>(),
        Utils::floatToDoubleRound(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scoreBase(), 2));

    EXPECT_STREQ(alert.at("vulnerability").at("enumeration").get_ref<const std::string&>().c_str(), "CVE");
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("architecture").get_ref<const std::string&>().c_str(),
                 scanContext->packageArchitecture().data());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("name").get_ref<const std::string&>().c_str(),
                 scanContext->packageName().data());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("version").get_ref<const std::string&>().c_str(),
                 scanContext->packageVersion().data());

    EXPECT_STREQ(alert.at("vulnerability").at("published").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->datePublished()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->reference()->c_str());
    EXPECT_STREQ(
        alert.at("vulnerability").at("severity").get_ref<const std::string&>().c_str(),
        Utils::toSentenceCase(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->severity()->str()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("status").get_ref<const std::string&>().c_str(), "Active");

    EXPECT_STREQ(alert.at("vulnerability").at("title").get_ref<const std::string&>().c_str(),
                 (CVEID + " affects " + scanContext->packageName().data()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("type").get_ref<const std::string&>().c_str(), "Packages");
    EXPECT_STREQ(alert.at("vulnerability").at("updated").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->dateUpdated()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("condition").get_ref<const std::string&>().c_str(),
                 "Package less than 1.0.0");
}

TEST_F(EventPackageAlertDetailsBuilderTest, TestSuccessfulPackageInsertedDefaultStatus)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_INSERTED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));
    auto scanContext = std::make_shared<TScanContext<TrampolineOsDataCache>>(syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"INSERTED"})"_json;
    scanContext->m_matchConditions[CVEID] = {"1.0.0", MatchRuleCondition::DefaultStatus};

    TEventPackageAlertDetailsBuilder<MockDatabaseFeedManager, TScanContext<TrampolineOsDataCache>>
        eventPackageAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(eventPackageAlertDetailsAugmentation.handleRequest(scanContext));

    auto& alert = scanContext->m_alerts[CVEID];

    EXPECT_STREQ(alert.at("vulnerability").at("package").at("condition").get_ref<const std::string&>().c_str(),
                 "Package default status");
}

TEST_F(EventPackageAlertDetailsBuilderTest, TestSuccessfulPackageInsertedLessThanOrEqual)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_INSERTED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));
    auto scanContext = std::make_shared<TScanContext<TrampolineOsDataCache>>(syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"INSERTED"})"_json;
    scanContext->m_matchConditions[CVEID] = {"1.0.0", MatchRuleCondition::LessThanOrEqual};

    TEventPackageAlertDetailsBuilder<MockDatabaseFeedManager, TScanContext<TrampolineOsDataCache>>
        eventPackageAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(eventPackageAlertDetailsAugmentation.handleRequest(scanContext));

    auto& alert = scanContext->m_alerts[CVEID];

    EXPECT_STREQ(alert.at("vulnerability").at("package").at("condition").get_ref<const std::string&>().c_str(),
                 "Package less than or equal to 1.0.0");
}

TEST_F(EventPackageAlertDetailsBuilderTest, TestSuccessfulPackageDeleted)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_DELETED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));
    auto scanContext = std::make_shared<TScanContext<TrampolineOsDataCache>>(syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"DELETED"})"_json;

    TEventPackageAlertDetailsBuilder<MockDatabaseFeedManager, TScanContext<TrampolineOsDataCache>>
        eventPackageAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(eventPackageAlertDetailsAugmentation.handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);
    EXPECT_NE(scanContext->m_elements.find(CVEID), scanContext->m_elements.end());

    EXPECT_EQ(scanContext->m_alerts.size(), 1);
    EXPECT_NE(scanContext->m_alerts.find(CVEID), scanContext->m_alerts.end());

    auto& alert = scanContext->m_alerts[CVEID];

    std::string alertScoreVersion {"cvss3"};

    EXPECT_STREQ(alert.at("vulnerability").at("cve").get_ref<const std::string&>().c_str(), CVEID.c_str());

    EXPECT_DOUBLE_EQ(
        alert.at("vulnerability").at("cvss").at(alertScoreVersion).at("base_score").get_ref<const double&>(),
        Utils::floatToDoubleRound(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scoreBase(), 2));

    EXPECT_STREQ(alert.at("vulnerability").at("enumeration").get_ref<const std::string&>().c_str(), "CVE");
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("architecture").get_ref<const std::string&>().c_str(),
                 scanContext->packageArchitecture().data());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("name").get_ref<const std::string&>().c_str(),
                 scanContext->packageName().data());
    EXPECT_STREQ(alert.at("vulnerability").at("package").at("version").get_ref<const std::string&>().c_str(),
                 scanContext->packageVersion().data());

    EXPECT_STREQ(alert.at("vulnerability").at("published").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->datePublished()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->reference()->c_str());
    EXPECT_STREQ(
        alert.at("vulnerability").at("severity").get_ref<const std::string&>().c_str(),
        Utils::toSentenceCase(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->severity()->str()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("status").get_ref<const std::string&>().c_str(), "Solved");

    EXPECT_STREQ(alert.at("vulnerability").at("title").get_ref<const std::string&>().c_str(),
                 (CVEID + " affecting " + scanContext->packageName().data() + " was solved").c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("type").get_ref<const std::string&>().c_str(), "Packages");
    EXPECT_STREQ(alert.at("vulnerability").at("updated").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->dateUpdated()->c_str());
}

TEST_F(EventPackageAlertDetailsBuilderTest, TestFailedInvalidOperation)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_deltas_SCHEMA));
    ASSERT_TRUE(parser.Parse(DELTA_PACKAGES_DELETED_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorDeltas::GetDelta(reinterpret_cast<const char*>(buffer));
    auto scanContext = std::make_shared<TScanContext<TrampolineOsDataCache>>(syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"invalid"})"_json;

    TEventPackageAlertDetailsBuilder<MockDatabaseFeedManager, TScanContext<TrampolineOsDataCache>>
        eventPackageAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_ANY_THROW(eventPackageAlertDetailsAugmentation.handleRequest(scanContext));
}
